package com.fh.module_main.view;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.fh.lib_base.config.AppConstants;
import com.fh.lib_base.util.SpHelper;
import com.fh.module_main.R;
import com.fh.module_main.data.CalendarDateBean;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 自定义日历选择器，仿华住会，美团酒店，携程酒店订房日历选择器
 */
public class CustomCalendarListView extends FrameLayout {

    RecyclerView recyclerView;
    CalendarAdapter adapter;
    private CalendarDateBean startDate;//开始时间
    private CalendarDateBean endDate;//结束时间
    OnDateSelected onDateSelected;//选中监听
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    static int currentTab;//0 全日房 1时租房 2民宿
    //获取到今天日期，用于比较今天之前的日期字体显示为不可点击
    Date todayDate = new Date();
    String today = simpleDateFormat.format(todayDate);

    public CustomCalendarListView(Context context) {
        super(context);
        init(context);
    }

    public CustomCalendarListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CustomCalendarListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        addView(LayoutInflater.from(context).inflate(R.layout.main_calendar_item_calendar,this,false));
        currentTab = 0;//默认是全日房
        recyclerView = findViewById(R.id.recyclerView);
        adapter = new CalendarAdapter();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 7);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int i) {
                if (CalendarDateBean.item_type_month == adapter.data.get(i).getItemType()) {
                    return 7;
                } else {
                    return 1;
                }
            }
        });
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(adapter);
        //日期格式化
        adapter.data.addAll(days(SpHelper.INSTANCE.decodeString(AppConstants.SpKey.QUANRI_START_DATE), SpHelper.INSTANCE.decodeString(AppConstants.SpKey.QUANRI_END_DATE)));
        MyCalendarItemDecoration myItemD = new MyCalendarItemDecoration();
        recyclerView.addItemDecoration(myItemD);

        adapter.setOnRecyclerviewItemClick(new CalendarAdapter.OnRecyclerviewItemClick() {
            @Override
            public void onItemClick(View v, int position) {
                onClick(adapter.data.get(position));
            }
        });
        setState();
        adapter.notifyDataSetChanged();
    }

    private void onClick(CalendarDateBean dateBean) {
        if (dateBean.getItemType() == CalendarDateBean.item_type_month || TextUtils.isEmpty(dateBean.getDay())) {
            return;
        }
        try{
            todayDate = simpleDateFormat.parse(today);
        }catch (Exception e){
            e.printStackTrace();
        }
        //不让点击今天之前的日期，
        if(dateBean.getDate() != null && dateBean.getDate().before(todayDate)){
            return;
        }
        if(CustomCalendarListView.currentTab == 1){
            //如果没有选中开始日期则此次操作选中开始日期
            int start = adapter.data.indexOf(startDate);
            int end = adapter.data.size();
            for (; start < end; start++) {
                 adapter.data.get(start).setItemState(CalendarDateBean.ITEM_STATE_NORMAL);
            }
            startDate = dateBean;
            dateBean.setItemState(CalendarDateBean.ITEM_STATE_BEGIN_DATE);
            if(onDateSelected!=null){
                onDateSelected.selected(simpleDateFormat.format(startDate.getDate()),simpleDateFormat.format(endDate.getDate()));
            }
        }else{
            //如果没有选中开始日期则此次操作选中开始日期
            if (startDate == null) {
                startDate = dateBean;
                dateBean.setItemState(CalendarDateBean.ITEM_STATE_BEGIN_DATE);
            } else if (endDate == null) {
                //如果选中了开始日期但没有选中结束日期，本次操作选中结束日期

                //如果当前点击的结束日期跟开始日期一致 则不做操作
                if (startDate == dateBean) {

                } else if (dateBean.getDate().getTime() < startDate.getDate().getTime()) {
                    //当前点选的日期小于当前选中的开始日期 则本次操作重新选中开始日期
                    startDate.setItemState(CalendarDateBean.ITEM_STATE_NORMAL);
                    startDate = dateBean;
                    startDate.setItemState(CalendarDateBean.ITEM_STATE_BEGIN_DATE);
                } else {
                    //选中结束日期
                    endDate = dateBean;
                    endDate.setItemState(CalendarDateBean.ITEM_STATE_END_DATE);
                    setState();

                    if(onDateSelected!=null){
                        onDateSelected.selected(simpleDateFormat.format(startDate.getDate()),simpleDateFormat.format(endDate.getDate()));
                    }
                }
            } else if (startDate != null && endDate != null) {
                //结束日期和开始日期都已选中
                clearState();
                //重新选择开始日期,结束日期清除
                startDate.setItemState(CalendarDateBean.ITEM_STATE_NORMAL);
                startDate = dateBean;
                startDate.setItemState(CalendarDateBean.ITEM_STATE_BEGIN_DATE);

                endDate.setItemState(CalendarDateBean.ITEM_STATE_NORMAL);
                endDate = null;
            }
        }
        adapter.notifyDataSetChanged();
    }

    //选中中间的日期
    private void setState() {
        if (endDate != null && startDate != null) {
            int start = adapter.data.indexOf(startDate);
            start += 1;
            int end = adapter.data.indexOf(endDate);
            for (; start < end; start++) {

                CalendarDateBean dateBean = adapter.data.get(start);
                if (!TextUtils.isEmpty(dateBean.getDay())) {
                    dateBean.setItemState(CalendarDateBean.ITEM_STATE_SELECTED);
                }
            }
        }
    }

    //取消选中状态
    private void clearState() {
        if (endDate != null && startDate != null) {
            int start = adapter.data.indexOf(startDate);
            start += 1;
            int end = adapter.data.indexOf(endDate);
            for (; start < end; start++) {
                CalendarDateBean dateBean = adapter.data.get(start);
                dateBean.setItemState(CalendarDateBean.ITEM_STATE_NORMAL);
            }
        }
    }

    //日历adapter
    public static class CalendarAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        ArrayList<CalendarDateBean> data = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //获取到今天日期，用于比较今天之前的日期字体显示为不可点击
        Date todayDate = new Date();
        String today = dateFormat.format(todayDate);

        private CalendarAdapter.OnRecyclerviewItemClick onRecyclerviewItemClick;

        public CalendarAdapter.OnRecyclerviewItemClick getOnRecyclerviewItemClick() {
            return onRecyclerviewItemClick;
        }
        public void setOnRecyclerviewItemClick(CalendarAdapter.OnRecyclerviewItemClick onRecyclerviewItemClick) {
            this.onRecyclerviewItemClick = onRecyclerviewItemClick;
        }
        @Override
        public int getItemCount() {
            return data.size();
        }
        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
            if (position == CalendarDateBean.item_type_day) {
                View rootView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.main_calendar_item_day, viewGroup, false);

                final CalendarAdapter.DayViewHolder dayViewHolder = new CalendarAdapter.DayViewHolder(rootView);
                dayViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onRecyclerviewItemClick != null) {
                            onRecyclerviewItemClick.onItemClick(v, dayViewHolder.getLayoutPosition());
                        }
                    }
                });
                return dayViewHolder;
            } else if (position == CalendarDateBean.item_type_month) {
                View rootView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.main_calendar_item_month, viewGroup, false);
                final CalendarAdapter.MonthViewHolder monthViewHolder = new CalendarAdapter.MonthViewHolder(rootView);
                monthViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onRecyclerviewItemClick != null) {
                            onRecyclerviewItemClick.onItemClick(v, monthViewHolder.getLayoutPosition());
                        }
                    }
                });
                return monthViewHolder;
            }
            return null;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
            if (viewHolder instanceof CalendarAdapter.MonthViewHolder) {
                ((CalendarAdapter.MonthViewHolder) viewHolder).tv_month.setText(data.get(position).getMonthStr());
            } else {
                CalendarAdapter.DayViewHolder vh = ((CalendarAdapter.DayViewHolder) viewHolder);
                vh.tv_day.setText(data.get(position).getDay());
                vh.tv_check_in_check_out.setVisibility(View.GONE);
                CalendarDateBean dateBean = data.get(position);
                try{
                    todayDate = dateFormat.parse(today);
                }catch (Exception e){
                    e.printStackTrace();
                }

                if(CustomCalendarListView.currentTab == 1){
                     //设置item状态
                    if (dateBean.getItemState() == CalendarDateBean.ITEM_STATE_BEGIN_DATE) {
                        //开始日期或结束日期
                        vh.itemView.setBackgroundColor(Color.parseColor("#0385F7"));
                        vh.tv_day.setTextColor(Color.WHITE);
                        vh.tv_check_in_check_out.setVisibility(View.VISIBLE);
                        vh.tv_check_in_check_out.setText("入住");
                    } else {
                        //正常状态
                        if(dateBean.getDate() != null && dateBean.getDate().before(todayDate)){
                            vh.itemView.setBackgroundColor(Color.WHITE);
                            vh.tv_day.setTextColor(Color.parseColor("#999999"));
                        }else{
                            vh.itemView.setBackgroundColor(Color.WHITE);
                            vh.tv_day.setTextColor(Color.BLACK);
                        }
                    }
                }else{
                    //设置item状态
                    if (dateBean.getItemState() == CalendarDateBean.ITEM_STATE_BEGIN_DATE || dateBean.getItemState() == CalendarDateBean.ITEM_STATE_END_DATE) {
                        //开始日期或结束日期
                        vh.itemView.setBackgroundColor(Color.parseColor("#0385F7"));
                        vh.tv_day.setTextColor(Color.WHITE);
                        vh.tv_check_in_check_out.setVisibility(View.VISIBLE);
                        if (dateBean.getItemState() == CalendarDateBean.ITEM_STATE_END_DATE) {
                            vh.tv_check_in_check_out.setText("离店");
                        } else {
                            vh.tv_check_in_check_out.setText("入住");
                        }
                    } else if (dateBean.getItemState() == CalendarDateBean.ITEM_STATE_SELECTED) {
                        //选中状态
                        vh.itemView.setBackgroundColor(Color.parseColor("#63B3FA"));
                        vh.tv_day.setTextColor(Color.WHITE);
                    } else {
                        //判断是否早于今天，早于今天字体显示不可点颜色
                        if(dateBean.getDate() != null && dateBean.getDate().before(todayDate)){
                            vh.itemView.setBackgroundColor(Color.WHITE);
                            vh.tv_day.setTextColor(Color.parseColor("#999999"));
                        }else{
                            vh.itemView.setBackgroundColor(Color.WHITE);
                            vh.tv_day.setTextColor(Color.BLACK);
                        }
                    }
                }
            }
        }

        @Override
        public int getItemViewType(int position) {
            return data.get(position).getItemType();
        }

        public class DayViewHolder extends RecyclerView.ViewHolder {
            public TextView tv_day;
            public TextView tv_check_in_check_out;

            public DayViewHolder(@NonNull View itemView) {
                super(itemView);
                tv_day = itemView.findViewById(R.id.tv_day);
                tv_check_in_check_out = itemView.findViewById(R.id.tv_check_in_check_out);
            }
        }

        public class MonthViewHolder extends RecyclerView.ViewHolder {
            public TextView tv_month;

            public MonthViewHolder(@NonNull View itemView) {
                super(itemView);
                tv_month = itemView.findViewById(R.id.tv_month);
            }
        }

        public interface OnRecyclerviewItemClick {
            void onItemClick(View v, int position);
        }
    }

    /**
     * 生成日历数据
     */
    private List<CalendarDateBean> days(String selectStartDate,String selectEndDate) {
        List<CalendarDateBean> dateBeans = new ArrayList<>();
        try {
            Calendar calendar = Calendar.getInstance();
            //日期格式化
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat formatYYYYMM = new SimpleDateFormat("yyyy-MM");

            //起始日期
            Date startDate = new Date();
            calendar.setTime(startDate);

            //结束日期,在当前日期上加3个月
            calendar.add(Calendar.MONTH, 3);
            Date endDate = new Date(calendar.getTimeInMillis());

            //格式化开始日期和结束日期为 yyyy-mm-dd格式
            String startDateStr = format.format(startDate);
            startDate = format.parse(startDateStr);

            String endDateStr = format.format(endDate);
            endDate = format.parse(endDateStr);

            calendar.setTime(startDate);

            //把当前的日期设置为这个月的第一天,
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            Calendar monthCalendar = Calendar.getInstance();

            //按月生成日历 每行7个 最多6行 42个
            //每一行有七个日期  日 一 二 三 四 五 六 的顺序
            for (; calendar.getTimeInMillis() <= endDate.getTime(); ) {
                //月份item
                CalendarDateBean monthDateBean = new CalendarDateBean();
                monthDateBean.setDate(calendar.getTime());
                monthDateBean.setMonthStr(formatYYYYMM.format(monthDateBean.getDate()));
                monthDateBean.setItemType(CalendarDateBean.item_type_month);
                dateBeans.add(monthDateBean);

                //获取一个月结束的日期和开始日期
                monthCalendar.setTime(calendar.getTime());
                monthCalendar.set(Calendar.DAY_OF_MONTH, 1);

                //当前月加一个月
                monthCalendar.add(Calendar.MONTH, 1);
                monthCalendar.add(Calendar.DAY_OF_MONTH, -1);
                Date endMonthDay = monthCalendar.getTime();

                //重置为本月开始
                monthCalendar.set(Calendar.DAY_OF_MONTH, 1);

                for (; monthCalendar.getTimeInMillis() <= endMonthDay.getTime(); ) {
                    //生成单个月的日历

                    //处理一个月开始的第一天
                    if (monthCalendar.get(Calendar.DAY_OF_MONTH) == 1) {
                        //看某个月第一天是周几
                        int weekDay = monthCalendar.get(Calendar.DAY_OF_WEEK);
                        switch (weekDay) {
                            case 1:
                                //周日
                                break;
                            case 2:
                                //周一
                                addDatePlaceholder(dateBeans, 1, monthDateBean.getMonthStr());
                                break;
                            case 3:
                                //周二
                                addDatePlaceholder(dateBeans, 2, monthDateBean.getMonthStr());
                                break;
                            case 4:
                                //周三
                                addDatePlaceholder(dateBeans, 3, monthDateBean.getMonthStr());
                                break;
                            case 5:
                                //周四
                                addDatePlaceholder(dateBeans, 4, monthDateBean.getMonthStr());
                                break;
                            case 6:
                                addDatePlaceholder(dateBeans, 5, monthDateBean.getMonthStr());
                                //周五
                                break;
                            case 7:
                                addDatePlaceholder(dateBeans, 6, monthDateBean.getMonthStr());
                                //周六
                                break;
                        }
                    }

                    //生成某一天日期实体 日item
                    CalendarDateBean dateBean = new CalendarDateBean();
                    dateBean.setDate(monthCalendar.getTime());
                    dateBean.setDay(monthCalendar.get(Calendar.DAY_OF_MONTH) + "");
                    dateBean.setMonthStr(monthDateBean.getMonthStr());
                    if(selectStartDate.equals(format.format(monthCalendar.getTime()))){
                        dateBean.setItemState(CalendarDateBean.ITEM_STATE_BEGIN_DATE);
                        this.startDate = dateBean;
                    }else if(selectEndDate.equals(format.format(monthCalendar.getTime()))){
                        dateBean.setItemState(CalendarDateBean.ITEM_STATE_END_DATE);
                        this.endDate = dateBean;
                    }
                    dateBeans.add(dateBean);

                    //处理一个月的最后一天
                    if (monthCalendar.getTimeInMillis() == endMonthDay.getTime()) {
                        //看某个月第一天是周几
                        int weekDay = monthCalendar.get(Calendar.DAY_OF_WEEK);
                        switch (weekDay) {
                            case 1:
                                //周日
                                addDatePlaceholder(dateBeans, 6, monthDateBean.getMonthStr());
                                break;
                            case 2:
                                //周一
                                addDatePlaceholder(dateBeans, 5, monthDateBean.getMonthStr());
                                break;
                            case 3:
                                //周二
                                addDatePlaceholder(dateBeans, 4, monthDateBean.getMonthStr());
                                break;
                            case 4:
                                //周三
                                addDatePlaceholder(dateBeans, 3, monthDateBean.getMonthStr());
                                break;
                            case 5:
                                //周四
                                addDatePlaceholder(dateBeans, 2, monthDateBean.getMonthStr());
                                break;
                            case 6:
                                addDatePlaceholder(dateBeans, 1, monthDateBean.getMonthStr());
                                //周5
                                break;
                        }
                    }
                    //天数加1
                    monthCalendar.add(Calendar.DAY_OF_MONTH, 1);
                }
//                Log.d(TAG, "日期" + format.format(calendar.getTime()) + "----周几" + getWeekStr(calendar.get(Calendar.DAY_OF_WEEK) + ""));
                //月份加1
                calendar.add(Calendar.MONTH, 1);
            }
        } catch (Exception ex) {

        }
        return dateBeans;
    }

    //添加空的日期占位
    private void addDatePlaceholder(List<CalendarDateBean> dateBeans, int count, String monthStr) {
        for (int i = 0; i < count; i++) {
            CalendarDateBean dateBean = new CalendarDateBean();
            dateBean.setMonthStr(monthStr);
            dateBeans.add(dateBean);
        }
    }

    public interface OnDateSelected{
        void selected(String startDate,String endDate);
    }

    public void setOnDateSelected(OnDateSelected onDateSelected,int currentTab) {
        this.onDateSelected = onDateSelected;
        this.currentTab = currentTab;
    }
}
